package com.penghaonan.appframework.utils

import android.text.TextUtils
import android.util.Log

class Logger {
    companion object {

        private val DEF_TAG = Logger::class.java.simpleName

        @JvmStatic
        var enable = false

        @JvmStatic
        fun isDebug(): Boolean {
            return enable
        }

        @JvmStatic
        fun i(tag: String?, msg: String?) {
            log(Log.INFO, tag, msg)
        }

        @JvmStatic
        fun e(tag: String?, msg: String?) {
            log(Log.ERROR, tag, msg)
        }

        @JvmStatic
        fun i(msg: String?) {
            i(autoTag(), msg)
        }

        inline fun i(log: () -> String) {
            if (enable) {
                i(autoTag(), log())
            }
        }

        @JvmStatic
        fun e(msg: String?) {
            e(autoTag(), msg)
        }

        inline fun e(log: () -> String) {
            if (enable) {
                e(autoTag(), log())
            }
        }

        @JvmStatic
        fun e(e: Exception) {
            e(e.toString())
            if (enable) {
                e.printStackTrace()
            }
        }

        @JvmStatic
        fun e(e: Throwable) {
            e(e.toString())
        }

        @JvmStatic
        fun debug(e: Exception) {
            e(e)
            DebugUtils.assertNull(e)
        }

        inline fun tmp(log: () -> String) {
            if (enable) {
                e("log_tmp", log())
            }
        }

        @JvmStatic
        fun tmp(log: String) {
            e("log_tmp", log)
        }

        @JvmStatic
        fun log(priority: Int, tag: String?, msg: String?) {
            if (enable) {
                Log.println(priority, tag, msg!!)
            }
        }

        @JvmStatic
        fun autoTag(): String? {
            if (!enable) {
                return DEF_TAG
            }
            val elements = Throwable().stackTrace
            val loggerClsName = Logger::class.java.simpleName
            for (i in 1 until elements.size) {
                val fileName = getFileName(elements[i])
                if (loggerClsName != fileName) {
                    return fileName
                }
            }
            return DEF_TAG
        }

        @JvmStatic
        private fun getFileName(element: StackTraceElement): String {
            val fileName = element.fileName ?: return ""
            val endIndex = fileName.indexOf(".").let {
                if (it < 0) {
                    fileName.length - 1
                } else {
                    it
                }
            }
            return if (TextUtils.isEmpty(fileName)) {
                ""
            } else fileName.substring(0, endIndex)
        }
    }
}